AppID="46385963"
APIKEY="BWN9pwIZx6aoSjhSeGEiFikd"
secret_key="1cNeE3iG2czhcRtjsLrEuOul100bxKNI"

import ischinese
import requests,os
import json,time
import pandas as pd

def get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+APIKEY+"&client_secret="+secret_key
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")

def main_google(i,theme,name):
    apikey='AIzaSyB3Jt8f4F1PZZR9dk6MViQ1O-xnfti90nU'
    '''    
    秘钥:AIzaSyBsGFRYULu1yRMA_H-gdU4OvGivvqJDClM
    秘钥:AIzaSyD6tcwFInavhIbiniCsjsXiMWFNlpGgMOY
    秘钥:AIzaSyB7sK0vG1nRS8R9DK0QIG4F-p5Ncp2yhHc
    秘钥:AIzaSyAaVtOrZbUVkjeTvzvIw94__QGUlfmzGko
    '''
    url = f'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={apikey}'
    headers = {'Content-Type': 'application/json'}
    data = {
        'contents': [
            {
                'parts': [
                    {
                        'text': '''If you are a chef at a five-star hotel, skilled in making creative dishes. Please make a dish of %s for 8 people that is suitable for American taste and themed around %s for your guests. Require that raw materials are easily available in supermarkets in the United States. Please list the ingredients and weight, preparation time, cooking time, cooking difficulty (1-5 levels, from simple to difficult), preparation method steps, nutritional ingredient list (including calories), dish characteristics, and 3-5 user comments. If there are any special precautions, please also list tips. The reply text must be output in full English, I don't understand Chinese characters. The output format should be:\n**[Dish Name]**\n\n**Ingredients and Weight**:\n\n[Ingredients and Weight]\n\n**Preparation Time**:\n\n[Preparation Time]\n\n**Preparation Time**:\n\n[Preparation Time]\n\n**Difficulty Level**:\n\n[Difficulty Level]\n\n**Preparation Method Steps**:\n\n[Preparation Method Steps]\n\n**Nutritional Information**:\n\n[Nutritional Information]\n\n**Dish Characteristics**:\n\n[Dish Characteristics]\n\n**User Comments**:\n\n[User Comments]\n\n**Special Precautions and Tips**:\n\n[Special Precautions and Tips]\n\n'''%(name,theme)
                        }
                    ]
                }
            ]
        }
    try:
        response = requests.post(url, headers=headers, data=json.dumps(data))
    except requests.exceptions.RequestException:
        return False
    response_text = response.json()
    print(response_text)
    if 'candidates' not in response_text or 'content' not in response_text['candidates'][0] or 'parts' not in response_text['candidates'][0]['content'] or 'text' not in response_text['candidates'][0]['content']['parts'][0]: return False
    result = response_text['candidates'][0]['content']['parts'][0]['text']
    with open("./recipes/%d.md"%i,"w") as f:
        f.write(result+"\n")
    print(result)
    print(i)
    return True

def main(i,theme,name,token):
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=" + token
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": "If you are a chef at a five-star hotel, skilled in making creative dishes. Please make a dish of %s for 8 people that is suitable for American taste and themed around %s for your guests. Require that raw materials are easily available in supermarkets in the United States. Please list the ingredients and weight, preparation time, cooking time, cooking difficulty (1-5 levels, from simple to difficult), preparation method steps, nutritional ingredient list (including calories), dish characteristics, and 3-5 user comments. If there are any special precautions, please also list tips. The reply text must be output in full English, I don't understand Chinese characters. The output format should be:\n**[Dish Name]**\n\n**Ingredients and Weight**:\n\n[Ingredients and Weight]\n\n**Preparation Time**:\n\n[Preparation Time]\n\n**Preparation Time**:\n\n[Preparation Time]\n\n**Difficulty Level**:\n\n[Difficulty Level]\n\n**Preparation Method Steps**:\n\n[Preparation Method Steps]\n\n**Nutritional Information**:\n\n[Nutritional Information]\n\n**Dish Characteristics**:\n\n[Dish Characteristics]\n\n**User Comments**:\n\n[User Comments]\n\n**Special Precautions and Tips**:\n\n[Special Precautions and Tips]\n\n"%(name,theme)
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }
    try:
        response = requests.request("POST", url, timeout=120, headers=headers, data=payload)
    except requests.exceptions.RequestException:
        return False
    if ischinese.judge(response.text): return False
    result = json.loads(response.text)
    if 'result' not in result: return False
    else:
        with open("./recipes/%d.md"%i,"w") as f:
            f.write(result['result']+"\n")
    print(response.text)
    print(i)
    return True
    
import sys
if __name__ == '__main__':
    lists = []
    for line in os.popen("ls recipes/*.md").read().split("\n"):
        if "/" not in line: continue
        name = line.split("/")[1].split(".")[0]
        lists.append(int(name))
    lists = sorted(lists)
    print(len(lists))
    if len(sys.argv) > 1: lists = [int(sys.argv[1])]
    file = pd.read_excel("allrecipes.xlsx")
    #token = get_access_token()
    for i in lists:
        if i < 60871: continue
        if i >= 61000: break
        url = file.iloc[i]['URL']
        name = file.iloc[i]['菜名']
        theme = file.iloc[i]['分类']
        #with open("a.a","w") as f: f.write(str(i)+"\n"+name+"\n")
        print(name,theme)
        ret = main_google(i,theme,name)
        cnt = 0
        while ret == False and cnt < 10:
            cnt += 1
            time.sleep(3) 
            ret = main_google(i,theme,name)
        if cnt<10:time.sleep(10) 
        else: break
